using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PhotonClone : MonoBehaviour
{
	public Transform lobbyParent;

	public Transform roomsParent;

	public Transform activeMatchesParent;

	public float timeToJoin = 0.2f;

	public float timeToCreate = 0.2f;

	protected List<FakeRoom> rooms = new List<FakeRoom>();

	public Coroutine CreateRoom(MatchTestPlayer player, FakeRoom room)
	{
		return StartCoroutine(WaitAndExecute(timeToCreate, delegate
		{
			DoCreateRoom(player, room);
		}));
	}

	public IEnumerator WaitAndExecute(float time, VoidDelegate d)
	{
		yield return new WaitForSeconds(time);
		d();
	}

	public void DoCreateRoom(MatchTestPlayer player, FakeRoom room)
	{
		Transform transform = new GameObject(room.name).transform;
		transform.parent = roomsParent;
		room.roomTransform = transform;
		room.Add(player);
		rooms.Add(room);
		Debug.Log("ROOM CREATED " + room.name + " c0 " + room.c0);
	}

	public Coroutine JoinRandomRoom(MatchTestPlayer player, FloatRange filter)
	{
		return StartCoroutine(WaitAndExecute(timeToJoin, delegate
		{
			DoJoinRandomRoom(player, filter);
		}));
	}

	public void DoJoinRandomRoom(MatchTestPlayer player, FloatRange filter)
	{
		Debug.Log("JOIN RANDOM ROOM - " + player.name + " filter" + filter.ToString());
		foreach (FakeRoom room in rooms)
		{
			if (filter.isIncluding(room.c0) && !room.isPlayerInside(player))
			{
				room.Add(player);
				rooms.Remove(room);
				room.roomTransform.parent = activeMatchesParent;
				Debug.Log("MATCH CREATED - " + player.name + " filter" + filter.ToString() + " ROOM " + room.name + " c0 " + room.c0);
				break;
			}
		}
	}

	public void SendToLobby(MatchTestPlayer player)
	{
		player.transform.parent = lobbyParent;
	}

	public void RemoveRoom(FakeRoom room)
	{
		foreach (MatchTestPlayer player in room.players)
		{
			SendToLobby(player);
		}
		Object.Destroy(room.roomTransform.gameObject);
		room.roomTransform = null;
		rooms.Remove(room);
	}
}
